package constraints

import "math"

// GroupByCount 按指定数量分组
func (list *List[V]) GroupByCount(count int) (r []*List[V]) {
	list.rlock()
	groupLen := int(math.Ceil(float64(list.Length()) / 8))
	for i := 0; i < groupLen; i++ {
		a := &List[V]{}
		start := i * count
		end := int(math.Min(float64(start+count), float64(list.Length())))
		for j := start; j < end; j++ {
			a.push(list.At(j))
		}

		r = append(r, a)
	}
	list.runlock()
	return
}

func (list *List[V]) GroupByCustomKey(getKey func(item V) string) map[string]*List[V] {
	list.rlock()
	r := map[string]*List[V]{}
	for _, val := range list.Slice() {
		key := getKey(val)
		a, has := r[key]
		if !has {
			a = &List[V]{}
			r[key] = a
		}
		a.Push(val)
	}
	list.runlock()
	return r
}
